package com.wenda.service.impl;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wenda.dao.UserDao;
import com.wenda.entity.User;
import com.wenda.service.UserService;
import com.wenda.util.MailUtil;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;

	@Override
	public User getUser(String username, String password) {
		User user = new User();
		user.setNumber(username);
		user.setPassword(password);
		return userDao.findByNumberAndPassword(user);
	}

	@Override
	public boolean updateUser(User user) {
		return userDao.updateSelectiveByPrimaryKey(user) != 0;
	}

	@Override
	public String sendMial(String email) {
		// 判断邮箱是否存在
		User user = userDao.findByEmail(email);
		if (user == null) {
			return "邮箱不存在";
		}
		// 随机6位数验证码
		String verifycode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
		user.setVerifycode(verifycode);
		// 保存验证码
		int row = userDao.updateSelectiveByPrimaryKey(user);
		if (row == 0) {
			return "验证码获取失败";
		}
		// 将验证码发给用户
		try {
			MailUtil.send(email, "重置密码", "验证码：" + verifycode, false);
		} catch (MessagingException e) {
			e.printStackTrace();
			return "连接超时";
		}
		return "发送成功";
	}

	@Override
	public String resetPwd(User userForm) {
		String newPwd = userForm.getPassword();
		// 获取用户信息
		User user = userDao.findByEmail(userForm.getEmail());
		if (user == null) {
			return "邮箱错误";
		}
		if(!user.getVerifycode().equals(userForm.getVerifycode())) {
			return "验证码错误"; 
		}
		if(user.getPassword().equals(newPwd)) {
			return "新密码不能与原密码一致";
		}
		//更新密码
		user.setPassword(newPwd);
		int row = userDao.updateSelectiveByPrimaryKey(user);
		if(row == 0) {
			return "密码重置失败";
		}
		return "密码重置成功";
	}
}
